/*******************************************************************
 *
 * Copyright © 2008 - 2009  All Rights Reserved. 
 *
 * @Version : 1.0
 *
 * @Filename SimpleRandom.java
 *
 * @author wangyongdong
 *
 * @Eamil wangyongdong@webgame.com.cn
 *
 * @Date 2009-9-22 下午12:17:11
 *
 *******************************************************************/

package game.breeze.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;

import org.apache.commons.lang.math.RandomUtils;

/**
 * @author wangyongdong
 * 
 */
public class SimpleRandom {

	/**
	 * 标准样本空间为10000
	 */
	public static int RANDOM_MAX_INT = 10000;

	/**
	 * 命中样本为0
	 */
	public static int RANDOM_TARGET_INT = 0;

	/**
	 * 指定随机数分子 60%
	 * @param range
	 * @return
	 */

	public static boolean factor(int range) {

		int rand = RandomUtils.nextInt(SimpleRandom.RANDOM_MAX_INT);

		if (range > rand) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 指定随机数分母 1/4
	 * 
	 * @param rate
	 * @return
	 */
	public static boolean denominator(int rate) {
		
		if(rate<=SimpleRandom.RANDOM_MAX_INT)
		{
			return true;
		}
		
		int rand = RandomUtils.nextInt(rate);

		if (rand == SimpleRandom.RANDOM_TARGET_INT) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据指定的list 随机返回list中的某个对象
	 * 
	 * @param list
	 * @return
	 */
	public static Object random(List<Object> list) {
		int rand = RandomUtils.nextInt(list.size());

		return list.get(rand);
	}

	/**
	 * 根据指定的queue 随机返回queue中的某个对象
	 * 
	 * @param queue
	 * @return
	 */
	public static Object random(Queue<Object> queue) {

		int rand = RandomUtils.nextInt(queue.size());

		int i = 0;
		Object ret = new Object();
		for (Object object : queue) {
			if (i == rand) {
				ret = object;
				break;
			}
			i++;
		}

		return ret;
	}

	/**
	 * 根据指定的list 随机返加list中的指定数量的对象
	 * 
	 * @param list
	 * @param size
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List random(List list, int size) {

		Set<Integer> set = SimpleRandom.random(list.size(), size);

		List ret = new ArrayList();

		for (Integer rand : set) {
			ret.add(list.get(rand));
		}

		return ret;
	}

	/**
	 * 根据指定范围和指定的位数 返回不重覆的指定数量的随机数列
	 * 
	 * @param rate
	 *            范围
	 * @param size
	 *            随机数范围
	 * @return
	 */
	public static Set<Integer> random(int rate, int size) {

		if (size > rate)
			size = rate;

		Set<Integer> set = new HashSet<Integer>();

		while (size > 0) {
			int len = set.size();
			int rand = RandomUtils.nextInt(rate);
			set.add(rand);
			if (set.size() > len) {
				size--;
			}
		}

		return set;
	}
}
